<template>
    <SysDialog :title="dialog.title" :visible="dialog.visible" :width="dialog.width" :height="dialog.height"
        @onClose="onClose" @onConfirm="commit">
        <template v-slot:content>
            <el-form :model="addModel" ref="addFormRef" :rules="rules" label-width="80px" :inline="false"
                size="default">
                <el-form-item prop="categoryName" label="菜品分类">
                    <el-select v-model="addModel.categoryName" placeholder="请选择分类" size="default" style="width: 240px">
                        <el-option v-for="item in selectData" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="goodsName" label="菜品名">
                    <el-input v-model="addModel.goodsName"></el-input>
                </el-form-item>
                <el-form-item prop="orderId" label="菜品序号">
                    <el-input v-model="addModel.orderId"></el-input>
                </el-form-item>
                <el-form-item prop="status" label="是否热推">
                    <el-radio-group v-model="addModel.status">
                        <el-radio :value="'0'">否</el-radio>
                        <el-radio :value="'1'">是</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item prop="specs" label="规格">
                    <el-button type="primary" :icon="Plus" size="small" @click="addSpecs">添加</el-button>
                </el-form-item>
                <el-form-item v-for="num in addModel.specs.length" size="normal" :key="num">
                    <el-row>
                        <el-col :span="7" :offset="0">
                            <el-form-item :label="'名称' + num" size="small">
                                <el-input v-model="addModel.specs[num - 1].specsName"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7" :offset="0">
                            <el-form-item :label="'序号' + num" size="small">
                                <el-input v-model="addModel.specs[num - 1].orderId"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7" :offset="0">
                            <el-form-item :label="'价格' + num" size="small">
                                <el-input v-model="addModel.specs[num - 1].goodsPrice"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="3" :offset="0">
                            <el-button style="margin-left: 15px; margin-top: -10px;" :icon="Close" type="danger" plain
                                circle size="small" @click="deleteSpecs"></el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item prop="goodsUnit" label="菜品单位">
                    <el-input v-model="addModel.goodsUnit"></el-input>
                </el-form-item>
                <el-form-item prop="goodsImage" label="菜品图片">
                    <UploadImage @get-img="getImg" :oldUrl="oldUrl" :fileList="fileList"></UploadImage>
                </el-form-item>
                <el-form-item prop="goodsDesc" label="菜品详情">
                    <div style="border: 1px solid #ccc">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" :mode="mode" />
                        <Editor style="height: 280px; overflow-y: hidden;" v-model="valueHtml"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                    </div>
                </el-form-item>
            </el-form>
        </template>
    </SysDialog>
</template>

<script setup lang="ts">
import useSelectCategory from '@/module/category/useSelectCategory'
import '@wangeditor/editor/dist/css/style.css' //引入css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import UploadImage from '@/components/UploadImage.vue'
import SysDialog from '@/components/SysDialog.vue';
import useDialog from '@/tools/useDialog';
import { reactive, ref, nextTick, watch } from 'vue';
import { ElMessage, FormInstance, UploadUserFile } from 'element-plus';
import { EditType, NewType } from '@/type/BaseType';
import { GoodsType, SpecsType } from '@/api/goods/GoodsModel';
import useEditor from "@/module/goods/useEditor"
import { Close, Plus } from '@element-plus/icons-vue';
import { addGoodsApi, editGoodsApi } from '@/api/goods';
//下拉分类
const { selectData, getSelect } = useSelectCategory()
//编辑器
const { editorRef, valueHtml, mode, toolbarConfig, editorConfig, handleCreated } = useEditor()
//表单的ref属性
const addFormRef = ref<FormInstance>();
//图片初始值
const fileList = ref<Array<UploadUserFile>>([])
//回显的图片
const oldUrl = ref<Array<{ url: string }>>([])
//图片地址
const imgUrl = ref<Array<{ url: string }>>([])
//弹框属性
const { dialog, onClose, onConfirm, onShow } = useDialog()
//显示弹窗
const show = (type: string, row?: GoodsType) => {
    dialog.title = '新增'
    //清空新增里面的图片
    imgUrl.value = []
    oldUrl.value = []
    fileList.value = []
    addModel.specs = []
    getSelect()
    dialog.height = 700
    dialog.width = 870
    //设置默认的规格
    addSpecs()
    //编辑时显示出数据
    if (row && type == EditType.EDIT) {
        dialog.title = '编辑'
        nextTick(() => {
            Object.assign(addModel, row)
            //图片回显
            if (addModel.goodsImage) {
                //逗号分隔的字符串转为数组
                let imgs = addModel.goodsImage.split(",")
                for (let i = 0; i < imgs.length; i++) {
                    let img = {
                        name: '',
                        url: ''
                    }
                    img.name = imgs[i]
                    img.url = imgs[i]
                    fileList.value.push(img)
                    oldUrl.value.push({ url: imgs[i] })
                }
            }
            //编辑器回显
            valueHtml.value = addModel.goodsDesc
        })
    } else {
        nextTick(() => {
            //清空新增里的文本编辑器
            if (editorRef.value) {
                editorRef.value.clear()
            }
            //添加时清空规格
            addModel.specs = []
            //设置默认规格
            addModel.specs.push({
                goodsPrice: '',
                orderId: '',
                specsName: '',
            })
        })
    }
    onShow()
    //设置编辑的属性：0：新增、1：编辑
    addModel.type = type;
    //清空表单
    addFormRef.value?.resetFields()
}
//将方法显露出去给父组件调用
defineExpose({
    show
})
//表单绑定的对象
const addModel = reactive<GoodsType>({
    type: '',
    goodsId: '',
    categoryName: '',
    goodsName: '',
    goodsImage: '',
    goodsDesc: '',
    status: '0',
    goodsUnit: '',
    orderId: '',
    specs: []
})
//菜品详情的验证
const checkDesc = (rule: any, value: any, callback: any) => {
    if (editorRef.value.getText().length == 0) {
        callback(new Error('请填写菜品详情'))
    } else {
        callback()
    }
}
//菜品规格的验证
const checkSpecs = (rule: any, value: any, callback: any) => {
    if (addModel.specs.length == 0) {
        callback(new Error('请填写菜品规格'))
    } else {
        let tag = false
        addModel.specs.forEach((item: SpecsType) => {
            if (!item.specsName) {
                tag = false
                callback(new Error('请填写规格的名称'))
            } else if (!item.goodsPrice) {
                tag = false
                callback(new Error('请填写规格的价格'))
            } else if (!item.orderId) {
                tag = false
                callback(new Error('请填写规格的序号'))
            } else {
                tag = true
            }
        })
        if (tag) {
            callback()
        }
    }
}
//表单验证规则
const rules = reactive({
    categoryName: [{
        required: true,
        message: '请选择分类',
        trigger: "blur",
    },],
    goodsName: [{
        required: true,
        message: '请填写菜品名',
        trigger: "blur",
    },],
    orderId: [{
        required: true,
        message: '请填写序号',
        trigger: "blur",
    },],
    status: [{
        required: true,
        message: '请选择是否热推',
        trigger: "blur",
    },],
    goodsDesc: [{
        required: true,
        validator: checkDesc,
        trigger: "blur",
    },],
    specs: [{
        required: true,
        validator: checkSpecs,
        trigger: "blur",
    },],
    goodsImage: [{
        required: true,
        message: '请上传图片',
        trigger: "blur",
    },],
});
//图片上传地址
const getImg = (img: NewType) => {
    imgUrl.value = oldUrl.value.concat(img.newImgUrl)
    if (img.deleteUrl.length > 0) {
        let newArr = imgUrl.value.filter((x) => !img.deleteUrl.some((item) => x.url === item.url))
        imgUrl.value = newArr
    }
    //把图片路径拼接为逗号分隔的字符串
    let url = ""
    for (let i = 0; i < imgUrl.value.length; i++) {
        url = url + imgUrl.value[i].url + ","
    }
    addModel.goodsImage = url.substring(0, url.lastIndexOf(","))
}
//获取编辑器的数据
watch(
    () => valueHtml.value,
    (value) => {
        addModel.goodsDesc = value
    }
)
//添加规格按钮
const addSpecs = () => {
    addModel.specs.push({
        goodsPrice: '',
        orderId: '',
        specsName: '',
    })
}
//删除规格
const deleteSpecs = (num: number) => {
    addModel.specs.splice(num - 1, 1)
}
//注册事件
const emists = defineEmits(['onFresh'])
//提交表单
const commit = () => {
    addFormRef.value?.validate(async (valid) => {
        if (valid) {
            let result = null
            if (addModel.type == EditType.ADD) {
                result = await addGoodsApi(addModel)
            } else {
                result = await editGoodsApi(addModel)
            }
            if (result && result.code == 200) {
                ElMessage.success(result.msg)
                emists('onFresh')
                onClose()
            }
        }
    })
}
</script>

<style scoped></style>